﻿using WeDonekRpc.HttpApiGateway.Interface;
using WeDonekRpc.Helper;
using System.Collections.Generic;

namespace WeDonekRpc.HttpApiGateway.Model
{
    internal class RequestState : IState
    {
        private Dictionary<string, dynamic> _states = new Dictionary<string, dynamic>();

        public void Add<T>(string key, T value)
        {
            _states.Add(key, value);
        }
        public bool ContainsKey(string key)
        {
            return _states.ContainsKey(key);
        }
        public void AddOrSet<T>(string key, T value)
        {
            _states.AddOrSet(key, value);
        }

        public T GetOrDefault<T>(string key)
        {
            return _states.GetValueOrDefault(key, default(T));
        }

        public T GetOrDefault<T>(string key, T def)
        {
            return _states.GetValueOrDefault(key, def);
        }

        public void Set<T>(string key, T value)
        {
            if (!_states.ContainsKey(key))
            {
                throw new ErrorException("http.request.state.key.reapeat");
            }
            _states[key] = value;
        }

        public bool TryAdd<T>(string key, T value)
        {
            return _states.TryAdd(key, value);
        }
        public T Get<T>(string key)
        {
            return _states[key];
        }
        public bool TryGet<T>(string key, out T value)
        {
            if(_states.TryGetValue(key, out dynamic val))
            {
                value = val;
                return true;
            }
            value = default(T);
            return false;
        }
    }
}
